package com.jiubanqingchen.future.org.business.anonymous;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jiubanqingchen.future.common.enums.CacheName;
import com.jiubanqingchen.future.model.models.Anonymous;
import com.jiubanqingchen.future.model.models.User;
import com.jiubanqingchen.future.org.admin.ModelService;
import com.jiubanqingchen.future.org.annotation.Sqlkey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

@Sqlkey("anonymous.list")
public class AnonymousService extends ModelService<Anonymous> {

    private static Logger logger = LoggerFactory.getLogger(AnonymousService.class);

    /**
     * 得到匿名key
     *
     * @return
     */
    private List<String> getAnonymousUrlList() {
        List<String> urls = new ArrayList<>();
        try {
            List<Anonymous> anonymouList = Anonymous.dao.findByCache(CacheName.ANONYMOUS_LIST.getValue(), "anonymous", Db.getSql(getSqlKey()));
            if (anonymouList.isEmpty()) return urls;
            anonymouList.forEach(anonymous -> {
                urls.add(anonymous.getUrl());
            });
        } catch (Exception e) {
            logger.error("anonymouList", e);
        }
        return urls;
    }

    /**
     * 校验是否为匿名访问url
     *
     * @param url 请求地址
     * @return
     */
    public boolean judgeIsAnonymous(String url) {
        List<String> urls = getAnonymousUrlList();
        if (!urls.isEmpty()) return urls.contains(url);
        return false;
    }

    @Override
    public void afterSave(Anonymous anonymous, Record record, User _usr) throws Exception {
        super.afterSave(anonymous, record, _usr);
        CacheKit.remove(CacheName.ANONYMOUS_LIST.getValue(), "anonymous");
    }
}